/**
 * Created by FreezeSoul on 2017/7/21.
 */
'use strict';
define([
    "app/core/base",
    "app/core/util",
    "../commonMeta",
    "jquery",
    "underscore",
    'JSONParse',
    'loglevel',
    'Handsontable'
], function (Chart, Util, Meta, $, _, JSON, log, Handsontable) {

    //TODO:自定义组件属性
    var property = {
        config: "property",
        option: [
            {
                group: '基础',
                id: 'EXCEL_ZHI_DU',
                name: '只读',
                enable: false,
                type: 'checked',
                value: true,
                default: true,
                link: 'readOnly',
                tooltip: '表格数据只读'
            }, {
                group: '基础',
                id: 'EXCEL_LIE_PAI_XU',
                name: '列排序',
                enable: false,
                type: 'checked',
                value: false,
                default: false,
                link: 'columnSorting',
                tooltip: '表格列排序支持'
            }, {
                group: '基础',
                id: 'EXCEL_HANG_GAO_TIAO_ZHENG',
                name: '行高调整',
                enable: false,
                type: 'checked',
                value: false,
                default: false,
                link: 'manualRowResize',
                tooltip: '表格行高调整支持'
            }, {
                group: '基础',
                id: 'EXCEL_LIE_KUAN_TIAO_ZHENG',
                name: '列宽调整',
                enable: false,
                type: 'checked',
                value: false,
                default: false,
                link: 'manualColumnResize',
                tooltip: '表格列宽调整支持'
            }, {
                group: '基础',
                id: 'EXCEL_HANG_YI_DONG',
                name: '行可移动',
                enable: false,
                type: 'checked',
                value: false,
                default: false,
                link: 'manualRowMove',
                tooltip: '表格行可移动支持'
            }, {
                group: '基础',
                id: 'EXCEL_LIE_YI_DONG',
                name: '列可移动',
                enable: false,
                type: 'checked',
                value: false,
                default: false,
                link: 'manualColumnMove',
                tooltip: '表格列可移动支持'
            }, {
                group: '基础',
                id: 'EXCEL_HANG_DONG_JIE',
                name: '行冻结数',
                enable: false,
                type: 'number',
                value: 0,
                default: 0,
                link: 'fixedRowsTop',
                tooltip: '表格行冻结数'
            }, {
                group: '基础',
                id: 'EXCEL_LIE_DONG_JIE',
                name: '列冻结数',
                enable: false,
                type: 'number',
                value: 0,
                default: 0,
                link: 'fixedColumnsLeft',
                tooltip: '表格列冻结数'
            },
            {
                group: '绑定',
                id: 'EXCEL_BINDING',
                name: '数据绑定',
                enable: true,
                type: 'sortBinding',
                dataset: '',
                columns: [],
                tooltip: '表格数据绑定'
            },
            {
                group: '绑定',
                id: 'FilterName',
                name: '过滤列名称',
                enable: false,
                type: 'text',
                value: '',
                default: '',
                link: 'filterName',
                tooltip: '绑定数据集，客户端过滤字段列名称'
            },
            {
                group: '绑定',
                id: 'FilterValue',
                name: '过滤列默认值',
                enable: false,
                type: 'text',
                value: '',
                default: '',
                link: 'filterValue',
                tooltip: '绑定数据集，客户端过滤字段默认值'
            }
        ].concat($.extend(true, [], Meta.commonProperties)),
        MapOption: function (option) {
            Util.linkOption(this.option, option);
        }
    };

    var excel = Chart.extend({
        constructor: function (layout) {
            this._layout = layout;
            this._element = null;
            this._lastdata = null;
            this._container = null;
            this._option = {
                Binding: [],
                Events: [],
                Extend: $.extend(true, {}, property),
                Option: {
                    uuid: '',
                    class: '',
                    display: true,
                    readOnly: true,
                    rowHeaders: true,
                    colHeaders: true,
                    stretchH: 'all',
                    sortIndicator: true,
                    columnSorting: false,
                    contextMenu: false,
                    manualRowResize: false,
                    manualColumnResize: false,
                    manualRowMove: false,
                    manualColumnMove: false,
                    fixedRowsTop: 0,
                    fixedColumnsLeft: 0,
                    data: [],
                    initScript: '',
                    disposeScript: ''
                }
            };
        },
        init: function (element) {
            try {
                this._container = element;
            } catch (e) {
                log.error(e);
            }
        },
        _readProperty: function () {
            try {
                if (!this._option.Extend) return;
                Util.deepMapOption(property, this._option.Extend, this._option.Option);
            } catch (e) {
                log.error(e);
            }
        },
        _render: function (option) {
            $(this._container).empty();
            setTimeout(function () {
                $(window).trigger('resize');
            });
            var table = new Handsontable(this._container, option);

            //Util.setCommonMeta(this, this._container, this._option.Option);
            //Util.initChartLifeTime(this, this._container, this._option.Option);

            return table;
        },
        example: function () {
            try {
                var exampleOption = $.extend(true, {}, this._option.Option);
                exampleOption.data = Handsontable.helper.createSpreadsheetData(40, 6);
                this._element = this._render(exampleOption);
            } catch (e) {
                log.error(e);
            }
        },
        _bindEvent: function () {
            var _this = this;
            if (!this._filterDataHandle) {
                this._filterDataHandle = function (params) {
                    _this.filterDataHandle.call(_this, params);
                };
            }
            this._layout.removeListener("filterData", this._filterDataHandle);
            this._layout.addListener("filterData", this._filterDataHandle);
        },
        filterDataHandle: function (params) {
            var _this = this;
            var flag = false;
            var filterColumn = _.findWhere(this._option.Extend.option, {name: '过滤列名称'});
            var filterValue = _.findWhere(this._option.Extend.option, {name: '过滤列默认值'});

            if (filterColumn && filterValue
                && filterColumn.enable && filterValue.enable
                && filterColumn.value !== "" && filterValue.value !== ""
            ) {
                for (var prop in params) {
                    if (!params.hasOwnProperty(prop)) continue;
                    if (filterColumn.value === prop) {
                        filterValue.value = params[prop];
                        flag = true;
                    }
                }
            }
            if (flag && _this._lastdata) {
                _this.setData(_this._lastdata);
            }
        },
        _bindData: function (data) {
            var bindProperty = _.findWhere(this._option.Extend.option, {type: 'sortBinding'});
            if (!bindProperty) return;

            var dataSetCode = bindProperty.dataset;
            var columns = bindProperty.columns;
            var table = data[dataSetCode];
            var tableData = [];
            var tableHeader = [];
            _.each(columns, function (binding) {
                tableHeader.push(binding.ColumnName);
            });
            this._option.Option.colHeaders = tableHeader;
            table = this._filterTable(this._option.Extend.option, table);
            if (table && table.length > 0) {
                $.each(table, function (j, row) {
                    var rowData = [];
                    _.each(columns, function (binding) {
                        rowData.push(row[binding.ColumnName]);
                    });
                    tableData.push(rowData);
                });
                this._option.Option.data = tableData;
            }
        },
        _filterTable: function (option, table) {
            var filterColumn = _.findWhere(option, {name: '过滤列名称'});
            var filterValue = _.findWhere(option, {name: '过滤列默认值'});

            if (table && filterColumn && filterValue
                && filterColumn.enable && filterValue.enable
                && filterColumn.value !== "" && filterValue.value !== ""
            ) {
                var tableCopy = _.map(table, _.clone);
                return _.filter(tableCopy, function (row) {
                    return row[filterColumn.value] === filterValue.value;
                });
            }
            return table;
        },
        setData: function (data) {
            try {
                this._lastdata = data;

                this._readProperty();

                if (data
                    && this._option.Binding
                    && this._option.Binding.length > 0
                    && this._option.Extend
                ) {
                    this._bindData(data);

                    this._readProperty();
                }
                this._element = this._render(this._option.Option);
                this._bindEvent();
            } catch (e) {
                log.error(e);
            }
        },
        setOption: function (option) {
            try {
                return this._option = $.extend(true, {}, option);
            } catch (e) {
                log.error(e);
            }
        },
        getOption: function () {
            try {
                this._readProperty();
            } catch (e) {
                log.error(e);
            }
            return this._option;
        },
        setTheme: function (theme) {
            try {
            } catch (e) {
                log.error(e);
            }
        },
        resize: function () {
            try {
                if (this._element) {
                    this._element.render();
                }
            } catch (e) {
                log.error(e);
            }
        },
        showLoading: function () {
            try {
                if (this._layout && this._layout.showLoading) {
                    this._layout.showLoading(this);
                }
            } catch (e) {
                log.error(e);
            }
        },
        hideLoading: function () {
            try {
                if (this._layout && this._layout.hideLoading) {
                    this._layout.hideLoading(this);
                }
            } catch (e) {
                log.error(e);
            }
        },
        dispose: function () {
            try {
                this._layout.removeListener("filterData", this._filterDataHandle);
                //Util.disposeChartLifeTime(this, this._container, this._option.Option);

            } catch (e) {
                log.error(e);
            }
        },
        getElement: function () {
            return this._element;
        },
        getChart: function () {
            return this._element;
        }
    });

    return {
        Chart: excel,
        Property: property
    };
});